<template>
  <el-drawer v-model="self_drawer" :close-on-press-escape="true" :close-on-click-modal="true"
    @closed="() => emit('close')">
    <template #header>
      <span class="gradient-text">{{ title }}</span>
    </template>
    <p>{{ $t("ai.manual_fill_content") }}</p>
    <el-card shadow="never" style="overflow-y: auto; position: relative; border: none">
      <el-input :autosize="{ minRows: 12, maxRows: 12 }" v-model="perContent" placeholder="" type="textarea"></el-input>

      <div style="display: flex; justify-content: space-between">
        <el-button type="primary" link @click="handleReplacePer">{{
          $t("ai.replace")
        }}</el-button>
      </div>
    </el-card>
    <br />
    <!-- ai润色内容 -->
    <p>{{ $t("ai.ai_polishing_content") }}</p>
    <el-card shadow="never" style="padding: 10px; overflow-y: auto; position: relative" v-loading="loading">
      <div style="min-height: 230px; overflow: auto">
        <code> {{ replay }}</code>
      </div>

      <div style="display: flex; justify-content: space-between">
        <el-button type="primary" link @click="handleReplaceAi">{{
          $t("ai.replace")
        }}</el-button>
        <el-button type="primary" link :icon="Refresh" @click="getAiResponse(true)">{{
          $t("ai.re_polishing")
        }}</el-button>
      </div>
    </el-card>
  </el-drawer>
</template>

<script setup lang="ts">
import message from '@/utils/message'
import fetch from '@/api/fetch'
import { Refresh } from '@element-plus/icons-vue'
import { ref, watch, computed } from 'vue'
import { useI18n } from 'vue-i18n'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
  },
  content: {
    type: String,
    default: '',
  },
  aiContent: {
    type: String,
    default: '',
  },
})

const emit = defineEmits<{
  (event: 'update:modelValue', value: boolean): void
  (event: 'replace', value: string): void
  (event: 'close'): void
}>()



const title = ref('')
const replay = ref('')
const perContent = ref('')
const loading = ref(false)
const lock = ref(false)

const { t } = useI18n()

const getAiResponse = async (reload:boolean) => {
  if (lock.value) return
  loading.value = true
  if (reload) replay.value = ''
  try {
    lock.value = true

    const readableStream = await fetch.streamDialogue(props.content)
    if (readableStream) {
      loading.value = false
      const reader = readableStream.getReader()
      while (true) {
        const { done, value } = await reader.read()
        if (done) break

        const decoder = new TextDecoder('utf-8')
        const text = decoder.decode(value)

        const lines = text.split('\n').filter(Boolean)
        for (const line of lines) {
          try {
            const split = line.replace(/^data:\s*/, '')
            if (!split) continue
            const json = JSON.parse(split)

            if (json.code === 500) {
              message.error(json.msg)
              lock.value = false
              return (title.value = t('ai.polishing_fail'))
            }

            if (json.answer) {
              replay.value += json.answer
            }
          }
          catch (e) {
            continue
          }
        }
      }
      lock.value = false
      title.value = t('ai.polishing_success')
    }
  }
  catch (e) {
    console.error(e)
    lock.value = false
    loading.value = false

    replay.value = e + ''
    return (title.value = t('ai.polishing_fail'))
  }
}

const handleReplaceAi = () => {
  emit('replace', replay.value)
}

const handleReplacePer = () => {
  emit('replace', perContent.value)
}


// 双向绑定props
const self_drawer = computed({
  get: () => props.modelValue,
  set: (val) => {
    emit('update:modelValue', val)
  },
})

// 赋值数据
watch(
  () => props.content,
  (newContent) => {
    if (newContent) {
      perContent.value = newContent
      replay.value = props.aiContent
      // getAiResponse()
    }
  },
)
</script>

<style scoped lang="scss">
.gradient-text {
  background: linear-gradient(to right, #5091ff, #9d81ff, purple);
  -webkit-background-clip: text;
  color: transparent;
  margin-bottom: 0;
}


:deep(.el-card__body) {
  padding: 0 !important;
}
</style>

<style lang="scss">
header {
  margin-bottom: 0 !important;
}

.el-drawer__body {
  padding-top: 0 !important;
}
</style>
